package com.siyoumi.interceptor;

import com.siyoumi.component.XJwt;
import com.siyoumi.util.XLog;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.component.http.XHttpContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//对外api
@Slf4j
public class OpenApiInterceptor
        extends InterceptorBase
        implements HandlerInterceptor {
    /**
     * 执行前
     *
     * @return boolean
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("BEGIN");

        XReturn r = authToken();
        if (r.err()) {
            return returnErr(response, r);
        }
        XLog.debug(this.getClass(), r);

        String x = r.getData("x");
        XHttpContext.setX(x); //设置x
        XHttpContext.set(XHttpContext.keyTokenData, r);

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("END");
    }


    /**
     * 验证token
     *
     * @return 验证结果
     */
    protected XReturn authToken() {
        log.debug("检查token");
        String token = XHttpContext.getToken();
        if (XStr.isNullOrEmpty(token)) {
            return XReturn.getR(50550, "缺少令牌");
        }

        XJwt jwt = XJwt.getBean();
        XReturn r = jwt.parseToken(token);
        if (r.err()) {
            r.setErrCode(50510);
        }
        
        return r;
    }
}
